<template>
  <div class="app-container">
    <div v-show="active === 1">
      <div class="searchform">
        <!-- 查询条件 -->
        <el-form ref="searchForm" :inline="true" :model="search" size="mini" label-width="100px">
          <el-form-item prop="positionCode" label="职位代码">
            <el-input v-model="search.positionCode" placeholder="职位代码" class="search-input" clearable />
          </el-form-item>
          <el-form-item prop="positionName" label="职位名称">
            <el-input v-model="search.positionName" placeholder="职位名称" class="search-input" clearable />
          </el-form-item>
          <div style="text-align:center">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="searchHandle">查询
              </el-button>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-refresh" @click="resetForm('searchForm')">重置
              </el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <!-- 用户列表 -->
      <div class="table">
        <div class="tableHead">
          <div class="btnGroup">职位信息</div>
          <div class="btnGroup">
            <el-button-group>
              <el-button type="primary" icon="el-icon-plus" @click="add">新增
              </el-button>
            </el-button-group>
          </div>
        </div>
        <BaseTable ref="table" @chaneg-size="changeSizeHandle" @chaneg-page="changePageHandle">
          <el-table-column type="index" label="序号" min-width="20"/>
          <el-table-column align="center" label="操作" min-width="20">
            <template slot-scope="scope">
              <el-tooltip class="item" content="编辑" placement="bottom">
                <el-button type="text" style="font-size: 20px;" icon="el-icon-edit-outline" @click="edit(scope.row)"/>
              </el-tooltip>
              <el-tooltip class="item" content="明细" placement="bottom">
                <el-button type="text" style="font-size: 20px;" icon="el-icon-document" @click="detail(scope.row)"/>
              </el-tooltip>

            </template>
          </el-table-column>
          <el-table-column prop="POSITION_CODE" label="职位代码" min-width="50"/>
          <el-table-column prop="POSITION_NAME" label="职位名称" min-width="50"/>
        </BaseTable>
      </div>
    </div>
    <!-- 新增div -->
    <div v-show="active === 2">
      <div class="searchform">
        <el-form ref="addSearchForm" :inline="true" :model="addSearch" :rules="rules" size="mini" label-width="90px">
          <el-form-item prop="positionCode" label="职位代码">
            <el-input v-model="addSearch.positionCode" placeholder="职位代码" class="search-input" maxlength="10" minlength="4" clearable />
          </el-form-item>
          <el-form-item prop="positionName" label="职位名称">
            <el-input v-model="addSearch.positionName" placeholder="职位名称" class="search-input" clearable />
          </el-form-item>
        </el-form>
      </div>
      <el-tabs v-model="activeName">
        <el-tab-pane label="已分配角色" name="first">
          <div class="table">
            <div class="tableHead">
              <div class="btnGroup">
                <el-button-group>
                  <el-button type="primary" icon="el-icon-plus" @click="openRole">添加</el-button>
                </el-button-group>
              </div>
            </div>

            <BaseTableNoPage ref="table1" @chaneg-size="changeSizeHandle" @chaneg-page="changePageHandle">
              <el-table-column type="index" label="序号" min-width="20"/>
              <el-table-column align="center" label="操作" min-width="20">
                <template slot-scope="scope">
                  <el-tooltip class="item" content="删除" placement="bottom">
                    <el-button type="text" style="font-size: 20px;" icon="el-icon-delete" @click="table1Delete(scope.$index, scope.row)"/>
                  </el-tooltip>

                </template>
              </el-table-column>
              <el-table-column prop="ROLE_CODE" label="角色代码" min-width="50"/>
              <el-table-column prop="ROLE_NAME" label="角色名称" min-width="50"/>
            </BaseTableNoPage>
          </div>
        </el-tab-pane>
        <el-tab-pane label="已分配组织" name="second">
          <div class="table">
            <div class="tableHead">
              <div class="btnGroup">
                <el-button-group>
                  <el-button type="primary" icon="el-icon-plus" @click="openDia">添加</el-button>
                </el-button-group>
              </div>
            </div>

            <BaseTableNoPage ref="table2" @chaneg-size="changeSizeHandle" @chaneg-page="changePageHandle">
              <el-table-column type="index" label="序号" min-width="20"/>
              <el-table-column align="center" label="操作" min-width="20">
                <template slot-scope="scope">
                  <el-tooltip class="item" content="删除" placement="bottom">
                    <el-button type="text" style="font-size: 20px;" icon="el-icon-delete" @click="table2Delete(scope.$index, scope.row)"/>
                  </el-tooltip>

                </template>
              </el-table-column>
              <el-table-column prop="data" label="部门代码" min-width="50"/>
              <el-table-column prop="text" label="部门名称" min-width="50"/>
            </BaseTableNoPage>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="clear">返回</el-button>
      </div>

    </div>
    <!-- 编辑div -->
    <div v-show="active === 3">
      <div class="searchform">
        <el-form ref="editSearchForm" :inline="true" :model="editSearch" size="mini" label-width="90px">
          <el-form-item prop="positionCode" label="职位代码">
            <el-input v-model="editSearch.positionCode" disabled placeholder="职位代码" class="search-input" clearable />
          </el-form-item>
          <el-form-item prop="positionName" label="职位名称">
            <el-input v-model="editSearch.positionName" disabled placeholder="职位名称" class="search-input" clearable />
          </el-form-item>
        </el-form>
      </div>
      <el-tabs v-model="activeName">
        <el-tab-pane label="已分配角色" name="first">
          <div class="table">
            <div class="tableHead">
              <div class="btnGroup">
                <el-button-group>
                  <el-button type="primary" icon="el-icon-plus" @click="openRole">添加</el-button>
                </el-button-group>
              </div>
            </div>

            <BaseTableNoPage ref="edittable1" @chaneg-size="changeSizeHandle" @chaneg-page="changePageHandle">
              <el-table-column type="index" label="序号" min-width="20"/>
              <el-table-column align="center" label="操作" min-width="20">
                <template slot-scope="scope">
                  <el-tooltip class="item" content="删除" placement="bottom">
                    <el-button type="text" style="font-size: 20px;" icon="el-icon-delete" @click="edittable1Delete(scope.$index, scope.row)"/>
                  </el-tooltip>

                </template>
              </el-table-column>
              <el-table-column prop="ROLE_CODE" label="角色代码" min-width="50"/>
              <el-table-column prop="ROLE_NAME" label="角色名称" min-width="50"/>
            </BaseTableNoPage>
          </div>
        </el-tab-pane>
        <el-tab-pane label="已分配组织" name="second">
          <div class="table">
            <div class="tableHead">
              <div class="btnGroup">
                <el-button-group>
                  <el-button type="primary" icon="el-icon-plus" @click="openDia">添加</el-button>
                </el-button-group>
              </div>
            </div>

            <BaseTableNoPage ref="edittable2" @chaneg-size="changeSizeHandle" @chaneg-page="changePageHandle">
              <el-table-column type="index" label="序号" min-width="20"/>
              <el-table-column align="center" label="操作" min-width="50">
                <template slot-scope="scope">
                  <el-tooltip class="item" content="删除" placement="bottom">
                    <el-button type="text" style="font-size: 20px;" icon="el-icon-delete" @click="edittable2Delete(scope.$index, scope.row)"/>
                  </el-tooltip>

                </template>
              </el-table-column>
              <el-table-column prop="data" label="部门代码" min-width="50"/>
              <el-table-column prop="text" label="部门名称" min-width="50"/>
            </BaseTableNoPage>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button type="primary" @click="editSave">保存</el-button>
        <el-button @click="clear">返回</el-button>
      </div>

    </div>
    <!-- 明细div -->
    <div v-show="active === 4">
      <div class="searchform">
        <el-form ref="detailSearchForm" :inline="true" :model="editSearch" size="mini" label-width="90px">
          <el-form-item prop="positionCode" label="职位代码">
            <el-input v-model="editSearch.positionCode" disabled placeholder="职位代码" class="search-input" />
          </el-form-item>
          <el-form-item prop="positionName" label="职位名称">
            <el-input v-model="editSearch.positionName" disabled placeholder="职位名称" class="search-input" />
          </el-form-item>
        </el-form>
      </div>
      <el-tabs v-model="activeName">
        <el-tab-pane label="已分配角色" name="first">
          <BaseTableNoPage ref="detailtable1" @chaneg-size="changeSizeHandle" @chaneg-page="changePageHandle">
            <el-table-column type="index" label="序号" min-width="20"/>
            <el-table-column prop="ROLE_CODE" label="角色代码" min-width="50"/>
            <el-table-column prop="ROLE_NAME" label="角色名称" min-width="50"/>
          </BaseTableNoPage>
        </el-tab-pane>
        <el-tab-pane label="已分配组织" name="second">
          <BaseTableNoPage ref="detailtable2" @chaneg-size="changeSizeHandle" @chaneg-page="changePageHandle">
            <el-table-column prop="ORG_CODE" label="部门代码" min-width="50"/>
            <el-table-column prop="ORG_NAME" label="部门名称" min-width="50"/>
          </BaseTableNoPage>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button @click="clear">返回</el-button>
      </div>

    </div>
    <!-- 弹框 -->
    <el-dialog :visible.sync="dialogVisible" title="角色模板选择" width="70%">
      <!-- 查询条件 -->
      <div class="searchform">
        <el-form ref="searchForm" :inline="true" :model="roleSearch" size="mini" label-width="90px">
          <el-form-item prop="roleCode" label="角色代码">
            <el-input v-model="roleSearch.roleCode" placeholder="角色代码" class="search-input" clearable />
          </el-form-item>
          <el-form-item prop="roleName" label="角色名称">
            <el-input v-model="roleSearch.roleName" placeholder="角色名称" class="search-input" clearable />
          </el-form-item>
          <br>
          <div style="text-align:center">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="searchRole">查询
              </el-button>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-refresh" @click="resetForm('searchForm')">重置
              </el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <!-- 用户列表 -->
      <div class="table">
        <div class="tableHead">
          <div class="tabletitle">角色信息</div>
        </div>
        <el-table
          v-loading="load"
          ref="roleTable"
          :data="list"
          tooltip-effect="dark"
          style="width: 100%"
          stripe
          border
          @selection-change="handleSelectionChange">
          <el-table-column type="index" label="序号" width="50"/>
          <el-table-column type="selection" width="40"/>
          <el-table-column prop="ROLE_CODE" label="角色代码" min-width="50"/>
          <el-table-column prop="ROLE_NAME" label="角色名称" min-width="50"/>
        </el-table>
        <!-- 分页 -->
        <Pagination :data="page" @change-size="handleSizeChange" @change-page="handleCurrentChange" />
      </div>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <!-- <span slot="footer" class="dialog-footer"> -->
        <el-button type="primary" @click="req">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>

        <!-- </span> -->
      </div>
    </el-dialog>

    <el-dialog
      ref="dia"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="dialogFormVisible"
      :append-to-body="true"
      title="部门选择"
      custom-class="r-dialog"
      top="5vh"
      width="20%">
      <el-tree ref="tree" :data="jsonTree" show-checkbox node-key="id" highlight-current/>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button type="primary" @click="confirmHandle">确 定</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>

      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getPositionAuthList,
  getPositionAuthRoleModelList,
  getPositionAuthOrgList,
  getPositionAuthRoleList,
  groupSavePositionAuth,
  editSavePositionAuth
} from '@/api/admin/auth/gms/positionAuth'
import { getComOrgTreeList } from '@/api/admin/org/gms/companyOrgManage'
import Pagination from '@/components/Pagination'
import BaseTable from '@/components/BaseTable'
import BaseTableNoPage from '@/components/BaseTable/BaseTableNoPage'
import formMixins from '@/mixins/formMixins'
import {
  getJsonTree
} from '@/utils/index'
import _ from 'lodash'
import { systemCode } from '@/utils/validator'
export default {
  name: 'PogmsUsers',
  components: {
    BaseTable,
    BaseTableNoPage,
    Pagination
  },
  mixins: [formMixins],
  data() {
    const validatePositionCode = (rule, value, callback) => {
      if (value === undefined || value === '' || value === null) {
        callback(new Error('请输入职位代码'))
      } else {
        systemCode(rule, value, callback)
      }
    }
    return {
      type1: '',
      active: 1,
      activeName: 'first',
      form: {},
      list: [],
      load: false,
      page: {},
      multipleSelection: [],
      returnList: [],
      search: {
        limit: 10,
        pageNum: 1,
        positionCode: '',
        positionName: '',
        dataSource: '10451003',
        dataType: '10461001'
      },
      editSearch: {
        positionId: '',
        positionCode: '',
        positionName: ''
      },
      roleSearch: {
        limit: 10,
        pageNum: 1,
        roleCode: '',
        roleName: ''
      },
      addSearch: {
        positionCode: '',
        positionName: ''
      },
      dialogVisible: false,
      dialogFormVisible: false,
      tree: [],
      loading: false,
      rules: {
        positionCode: [{
          required: true,
          validator: validatePositionCode,
          trigger: 'blur'
        }],
        positionName: [{
          required: true,
          message: '请输入职位名称'
        }]
      }

    }
  },
  computed: {
    jsonTree() {
      this.tree.forEach(el => (el.label = el.text))
      this.tree.forEach(el => (el.parentId = el.parent))
      return getJsonTree(this.tree)
    }
  },
  mounted() {
    this.searchHandle()
  },
  methods: {
    // 查询
    searchHandle() {
      const table = this.$refs['table']
      const search = _.extend(this.search)
      table.wait()
      getPositionAuthList(search).then(res => {
        table.complete().filData(res)
      }).catch(err => {
        table.complete()
      })
    },
    // 查询角色模板选择列表
    openRole() {
      this.dialogVisible = true
      this.searchRole()
    },
    searchRole() {
      this.load = true
      getPositionAuthRoleModelList(this.roleSearch).then(res => {
        this.list = res.rows
        this.page = res
        this.load = false
      }).catch(err => {
        this.load = false
      })
    },
    // 新增
    add() {
      this.active = 2
      this.type1 = 'add'
      this.$nextTick(() => {
        this.$refs.addSearchForm.resetFields()
      })
    },
    // 编辑
    edit(data) {
      this.active = 3
      this.type1 = 'edit'
      const edittable1 = this.$refs['edittable1']
      const edittable2 = this.$refs['edittable2']
      edittable1.wait()
      const id = data.ORG_POSITION_ID
      const positionCode = data.POSITION_CODE
      const positionName = data.POSITION_NAME
      this.editSearch.positionId = id
      this.editSearch.positionCode = positionCode
      this.editSearch.positionName = positionName
      getPositionAuthRoleList(id).then(res => {
        edittable1.complete().filData(res)
      }).catch(err => {
        edittable1.complete()
      })
      edittable2.wait()
      getPositionAuthOrgList(id)
        .then(res => {
          res.forEach(item => {
            item['id'] = item.ORGDEPT_ID
            item['data'] = item.ORG_CODE
            item['text'] = item.ORG_NAME
          })
          edittable2.complete().filData(res)
        }).catch(err => {
          edittable2.complete()
        })
    },
    // 明细
    detail(data) {
      this.active = 4
      const edittable1 = this.$refs['detailtable1']
      const edittable2 = this.$refs['detailtable2']
      edittable1.wait()
      const id = data.ORG_POSITION_ID
      const positionCode = data.POSITION_CODE
      const positionName = data.POSITION_NAME
      this.editSearch.positionId = id
      this.editSearch.positionCode = positionCode
      this.editSearch.positionName = positionName
      getPositionAuthRoleList(id).then(res => {
        edittable1.complete().filData(res)
      }).catch(err => {
        edittable1.complete()
      })
      edittable2.wait()
      getPositionAuthOrgList(id).then(res => {
        edittable2.complete().filData(res)
      }).catch(err => {
        edittable2.complete()
      })
    },
    // 删除
    table1Delete(index, row) {
      const table1 = this.$refs.table1
      table1.delete(index)
    },
    table2Delete(index, row) {
      const table2 = this.$refs.table2
      table2.delete(index)
    },
    edittable1Delete(index, row) {
      const edittable1 = this.$refs.edittable1
      edittable1.delete(index)
    },
    edittable2Delete(index, row) {
      const edittable2 = this.$refs.edittable2
      edittable2.delete(index)
    },
    // 树加载
    searchTree() {
      this.loading = true
      getComOrgTreeList().then(res => {
        this.loading = false
        this.tree = res
      }).catch(err => {
        this.loading = false
      })
    },
    openDia() {
      this.dialogFormVisible = true
      this.$nextTick(() => {
        // const tree = this.$refs['tree']
        this.searchTree()
      })
    },
    // 树选择
    confirmHandle() {
      const list = this.$refs.tree.getCheckedNodes(true)
      debugger
      if (list.length === 0) {
        this.$message({
          type: 'info',
          message: '请选择数据!'
        })
        return false
      }
      const SelectListed = this.$refs.table2.data()
      const SelectListed1 = this.$refs.edittable2.data()
      if (!SelectListed.length === 0 && this.type1 === 'add') {
        for (let i = 0; i < SelectListed.length; i++) {
          for (let j = 0; j < list.length; j++) {
            if (SelectListed[i].id === list[j].id) {
              this.$message({
                type: 'info',
                message: '信息已存在，请重新选择!'
              })
              return
            }
          }
        }
      }
      if (!SelectListed1.length === 0 && this.type1 === 'edit') {
        for (let i = 0; i < SelectListed1.length; i++) {
          for (let j = 0; j < list.length; j++) {
            if (SelectListed1[i].id === list[j].id) {
              this.$message({
                type: 'info',
                message: '信息已存在，请重新选择!'
              })
              return
            }
          }
        }
      }
      this.$refs.table2.push(list)
      this.$refs.edittable2.push(list)
      this.dialogFormVisible = false
      this.$message({
        type: 'success',
        message: '添加成功!'
      })
    },
    // 角色列表选择
    handleSelectionChange(val) {
      debugger
      this.multipleSelection = val
    },
    req() {
      const val = this.multipleSelection
      if (val.length === 0) {
        this.$message({
          type: 'info',
          message: '请选择数据!'
        })
        return false
      }
      const SelectListed = this.$refs.table1.data()
      if (!SelectListed.length === 0 && this.type1 === 'add') {
        for (let i = 0; i < SelectListed.length; i++) {
          for (let j = 0; j < val.length; j++) {
            if (SelectListed[i].ROLE_ID === val[j].ROLE_ID) {
              this.$message({
                type: 'info',
                message: '信息已存在，请重新选择!'
              })
              return
            }
          }
        }
      }
      const SelectListed1 = this.$refs.edittable1.data()
      if (!SelectListed1.length === 0 && this.type1 === 'edit') {
        for (let i = 0; i < SelectListed1.length; i++) {
          for (let j = 0; j < val.length; j++) {
            if (SelectListed1[i].ROLE_ID === val[j].ROLE_ID) {
              this.$message({
                type: 'info',
                message: '信息已存在，请重新选择!'
              })
              return
            }
          }
        }
      }
      const table1 = this.$refs.table1
      const edittable1 = this.$refs.edittable1
      table1.rolePush(val)
      edittable1.rolePush(val)
      this.roleSearch.roleCode = ''
      this.roleSearch.roleName = ''
      this.dialogVisible = false
      this.$message({
        type: 'success',
        message: '添加成功!'
      })
    },
    // 角色选择分页
    handleSizeChange(size) {
      this.roleSearch.limit = size
      this.searchRole()
    },
    handleCurrentChange(page) {
      this.roleSearch.pageNum = page
      this.searchRole()
    },
    // 保存
    save() {
      this.$refs['addSearchForm'].validate((valid) => {
        if (valid) {
          const roleGmsSelectList = this.$refs.table1.data()
          roleGmsSelectList.forEach(item => {
            debugger
            item['roleId'] = item.ROLE_ID
            item['roleName'] = item.ROLE_NAME
          })
          const departGmsList = this.$refs.table2.data()
          departGmsList.forEach(item => {
            item['organizationId'] = item.id
            item['orgName'] = item.label
          })
          const data = {
            dataSource: '10451003',
            dataType: '10461001',
            positionCode: this.addSearch.positionCode,
            positionName: this.addSearch.positionName,
            departGmsList: departGmsList,
            roleGmsSelectList: roleGmsSelectList
          }
          groupSavePositionAuth(data).then(res => {
            this.$message({
              type: 'success',
              message: '保存成功!'
            })
            this.active = 1
            this.searchHandle()
          }).catch(err => {
            this.$message({
              type: 'error',
              message: err.response.data.errorMsg
            })
            return false
          })
        } else {
          this.$message({
            type: 'info',
            message: '请填写必填项!'
          })
          return false
        }
      })
    },
    // 编辑保存
    editSave() {
      const roleGmsSelectList = this.$refs.edittable1.data()
      roleGmsSelectList.forEach(item => {
        item['roleId'] = item.ROLE_ID
        item['roleName'] = item.ROLE_NAME
      })
      const departGmsList = this.$refs.edittable2.data()
      departGmsList.forEach(item => {
        item['organizationId'] = item.id
        item['orgName'] = item.label
      })
      debugger
      const positionId = this.editSearch.positionId
      const data = {
        dataSource: '10451003',
        dataType: '10461001',
        positionCode: this.editSearch.positionCode,
        positionName: this.editSearch.positionName,
        departGmsList: departGmsList,
        roleGmsSelectList: roleGmsSelectList
      }
      editSavePositionAuth(positionId, data).then(res => {
        this.$message({
          type: 'success',
          message: '保存成功!'
        })
        this.active = 1
        this.searchHandle()
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err.response.data.errorMsg
        })
        return false
      })
    },
    // 返回清空列表
    clear() {
      this.activeName = 'first'
      this.addSearch.positionCode = ''
      this.addSearch.positionName = ''
      const table1 = this.$refs['table1']
      table1.filData(this.returnList)
      const table2 = this.$refs['table2']
      table2.filData(this.returnList)
      const edittable1 = this.$refs['edittable1']
      edittable1.filData(this.returnList)
      const edittable2 = this.$refs['edittable2']
      edittable2.filData(this.returnList)
      debugger
      this.active = 1
    }
  }
}

</script>

<style scoped>

</style>
